
//
//  AddDoorSystemInfoViewController.m
//  RONGAO
//
//  Created by ZhangYeKun on 2017/2/28.
//  Copyright © 2017年 wei wang. All rights reserved.
//

#import "AddDoorSystemInfoViewController.h"
#import "DSDeviceInfoInputTableViewCell.h"
#import "FIDFMDBManager.h"
#import "MyServerDefined.h"
#import "BindCameraViewController.h"

@interface AddDoorSystemInfoViewController ()<UITableViewDelegate,UITableViewDataSource>
/** tableView **/
@property(nonatomic,strong) UITableView *tableView;
/** 下一步 **/
@property(nonatomic,strong) UIButton *nextButton;
/** plist配置文件 **/
@property(nonatomic,strong) NSArray *settingPlist;

@end

@implementation AddDoorSystemInfoViewController

- (void)viewDidLoad {
    
    [super viewDidLoad];
    [self setNavigationStyle];
    
}

#pragma mark - --------------------------touch event--------------------------
- (void)addDeviceAction{
    
    [[UIApplication sharedApplication] sendAction:@selector(resignFirstResponder) to:nil from:nil forEvent:nil];
    if ([self.dsModel.uid length] == 0 || [self.dsModel.uid length] != 20 || self.dsModel.uid == nil) {
        return [SVProgressHUD showErrorWithStatus:@"请输入正确的序列号"];
    }else if ([self.dsModel.view_pwd length] == 0|| self.dsModel.view_pwd == nil) {
        return [SVProgressHUD showErrorWithStatus:@"密码不能为空"];
    }else if ([self.dsModel.name length] == 0 || self.dsModel.name == nil) {
        return [SVProgressHUD showErrorWithStatus:@"名称不能为空"];
    }else if ([self.dsModel.name length] > 0 && [self.dsModel.uid length] == 20 && [self.dsModel.view_pwd length] > 0) {
        for (Camera *cam in [AppDelegate globalDelegate].camera_list) {
            
            if ([cam.uid isEqualToString:self.dsModel.uid]) {
                
                [SVProgressHUD showErrorWithStatus:@"此设备已存在"];
                return;
            }
        }

    }
   
    [self saveAndconnet];
    
    [SVProgressHUD showWithStatus:@"保存中..."];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        [SVProgressHUD dismiss];
        [self popViewController];

    });
    
    
}
#pragma mark - --------------------------摄像头保存连接部分--------------------------

- (void)saveAndconnet{
    
    
    
    NSLog(@"(long)self.indexView(long)self.indexView(long)self.indexView%@",[NSString stringWithFormat:@"%ld",(long)self.indexView]);
    
    MyCamera *camera = [[MyCamera alloc] initWithName:self.dsModel.name viewAccount:@"admin" viewPassword:self.dsModel.view_pwd];
    camera.isPushMode = 1;

    camera.nickname = self.dsModel.name;
    camera.name = self.dsModel.name;
    [camera connect:self.dsModel.uid];
    camera.cameraType = self.indexView;
    [camera start:0];
    
    SMsgAVIoctrlGetAudioOutFormatReq *s = (SMsgAVIoctrlGetAudioOutFormatReq *)malloc(sizeof(SMsgAVIoctrlGetAudioOutFormatReq));
    s->channel = 0;
    [camera sendIOCtrlToChannel:0 Type:IOTYPE_USER_IPCAM_GETAUDIOOUTFORMAT_REQ Data:(char *)s DataSize:sizeof(SMsgAVIoctrlGetAudioOutFormatReq)];
    free(s);
    
    SMsgAVIoctrlGetSupportStreamReq *s2 = (SMsgAVIoctrlGetSupportStreamReq *)malloc(sizeof(SMsgAVIoctrlGetSupportStreamReq));
    [camera sendIOCtrlToChannel:0 Type:IOTYPE_USER_IPCAM_GETSUPPORTSTREAM_REQ Data:(char *)s2 DataSize:sizeof(SMsgAVIoctrlGetSupportStreamReq)];
    free(s2);
    
    SMsgAVIoctrlSetTimeReq *s3 = (SMsgAVIoctrlSetTimeReq *)malloc(sizeof(SMsgAVIoctrlSetTimeReq));
    s3->time_second_0zone_ = [[NSDate date] timeIntervalSince1970];
    s3->diff_zone_minites_ = [[NSTimeZone localTimeZone] secondsFromGMT] / 60;
    
    [camera sendIOCtrlToChannel:0 Type:IOTYPE_USER_IPCAM_SET_TIME_REQ Data:(char *)s3 DataSize:sizeof(SMsgAVIoctrlSetTimeReq)];
    free(s3);
    NSLog(@"sendIOCtrlToChannel IOTYPE_USER_IPCAM_SET_TIME_REQ(uid:%@)", camera.uid);
    
    [[AppDelegate globalDelegate].camera_list
 addObject:camera];
    
    
    if ([AppDelegate globalDelegate].database
 != NULL) {
#if defined(P2PNETCAM_HAIER)
        [[AppDelegate globalDelegate].database
 executeUpdate:@"INSERT INTO device(dev_position, dev_uid, dev_nickname, dev_name, dev_pwd, view_acc, view_pwd, channel) VALUES(?,?,?,?,?,?,?,?)",
         position, camera.uid, name, name, password, @"admin", password, [NSNumber numberWithInt:0]];
#else

        [[AppDelegate globalDelegate].database
 executeUpdate:@"INSERT INTO device(dev_uid, dev_nickname, dev_name, dev_pwd, view_acc, view_pwd, channel,indexView) VALUES(?,?,?,?,?,?,?,?)",
        self.dsModel.uid, self.dsModel.name, self.dsModel.name, self.dsModel.view_pwd, self.dsModel.view_acc, self.dsModel.view_pwd, [NSNumber numberWithInt:0],[NSString stringWithFormat:@"%ld",(long)self.indexView]];
#endif
        
        [[AppDelegate globalDelegate].database
 executeUpdate:@"INSERT INTO notification(dev_uid, push_notification) VALUES(?,?)",
         camera.uid, [NSNumber numberWithInt:1]];
        
        
        [[AppDelegate globalDelegate] loadDeviceFromDatabase];

    }
    
    
    NSMutableString *uidListStr = [NSMutableString stringWithCapacity:20];
    NSMutableString *aliasListStr = [NSMutableString stringWithCapacity:20];
    NSMutableString *pushmodeListStr = [NSMutableString stringWithCapacity:20];
    NSMutableString *soundnameListStr = [NSMutableString stringWithCapacity:20];
    
    for (int i=0; i<[[AppDelegate globalDelegate].camera_list count]; i++) {
        MyCamera *camera = (MyCamera *)[[AppDelegate globalDelegate].camera_list objectAtIndex:i];
        NSString *uid = camera.uid;
        NSString *alias = camera.name;
        NSInteger pushmode = camera.isPushMode;
        NSString *soundname = camera.pushSoundName;
        NSLog(@"devUidList notificationList i=%d, uid:%@, alias=%@,  pushmode:%ld, soundname:%@",
              i, uid, alias, (long)pushmode, soundname);
        
        if (0 == i) {
            [uidListStr appendFormat:@"%@", uid];
            [aliasListStr appendFormat:@"%@", alias];
            [pushmodeListStr appendFormat:@"%ld", (long)pushmode];
            [soundnameListStr appendFormat:@"%@", soundname];
        } else {
            [uidListStr appendFormat:@":%@", uid];
            [aliasListStr appendFormat:@":%@", alias];
            [pushmodeListStr appendFormat:@":%ld", (long)pushmode];
            [soundnameListStr appendFormat:@":%@", soundname];
        }
    }
    NSLog(@"uidListStr:%@", uidListStr);
    NSLog(@"aliasListStr:%@", aliasListStr);
    NSLog(@"pushmodeListStr:%@", pushmodeListStr);
    NSLog(@"soundnameListStr:%@", soundnameListStr);
    
    NSInteger count = [[AppDelegate globalDelegate].camera_list count];

    NSLog(@"count:%ld", (long)count);
    if (count > 0) {
        
        dispatch_queue_t queue = dispatch_queue_create("myserver_maplist", NULL);
        dispatch_async(queue, ^{
            
            for (int i=0; i<120; i++) {
                if ([AppDelegate globalDelegate].deviceTokenString != nil) {
                    break;
                }
                //        NSLog(@"loadEventNotificationFromDatabase deviceTokenString==nil");
                usleep(500*1000);
            }
            
            if ([AppDelegate globalDelegate].deviceTokenString != nil) {
                

                [self pushMapDeviceList:count listId:uidListStr listPushMode:pushmodeListStr listAlias:aliasListStr listSoundName:soundnameListStr];
            }
            
        });
        
        
    } else {
        NSLog(@"No uid!!!");
    }
    
    
    

    
    // register to apns server
    dispatch_queue_t queue = dispatch_queue_create("apns-reg_client", NULL);
    dispatch_async(queue, ^{
        if ([AppDelegate globalDelegate].deviceTokenString != nil) {
            NSError *error = nil;
            NSString *appidString = [[NSBundle mainBundle] bundleIdentifier];
            //NSString *hostString = @"http://push.iotcplatform.com/apns/apns.php";
            NSString *hostString = @"http://120.26.128.42:8088/DOOR_Server/server.php";//
            NSString *argsString = @"%@?cmd=reg_mapping&token=%@&uid=%@&appid=%@";
            NSString *getURLString = [NSString stringWithFormat:argsString, hostString, [AppDelegate globalDelegate].deviceTokenString, self.dsModel.uid, appidString];
            NSLog(@"%@", getURLString);
            NSString *registerResult = [NSString stringWithContentsOfURL:[NSURL URLWithString:getURLString] encoding:NSUTF8StringEncoding error:&error];
            
            NSLog(@"%@", registerResult);
        }
    });


}


- (void)pushMapDeviceList:(NSInteger)count listId:(NSString *)listIdStr listPushMode:(NSString *)listPushModeStr listAlias:(NSString *)listAliasStr listSoundName:(NSString *)listSoundNameStr {
    
    NSString *param = [NSString stringWithFormat:@"cmd=updatedev&token=%@&ostype=%@&devcount=%ld&devidlist=%@&pushallow=%@&devaliaslist=%@&soundlist=%@&appn=%@", [AppDelegate globalDelegate].deviceTokenString, @"ios", (long)count, listIdStr, listPushModeStr, listAliasStr, listSoundNameStr, XG_APPN_STR];
    
    
    NSString *cmd = [NSString stringWithFormat:@"%@?%@", SZY, param];
    NSLog(@"cmd:%@", cmd);
    
    NSString *dataUTF8 = [cmd stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSLog(@"dataUTF8:%@", dataUTF8);
    cmd = dataUTF8;
    
    CommonHttp *commonHttp = [[CommonHttp alloc] init];
    NSData *recervedData;
    recervedData = [commonHttp reqHttpGetMode:cmd];
    
    NSString *servercmd = @"";
    NSString *servercode = @"";
    NSString *servermsg = @"";
    if (recervedData) {
        NSDictionary *jsonData = [NSJSONSerialization JSONObjectWithData:recervedData options:0 error:nil];
        
        servercmd = [jsonData objectForKey:@"cmd"];
        servercode = [jsonData objectForKey:@"code"];
        servermsg = [jsonData objectForKey:@"msg"];
        
        NSLog(@"cmd=%@ code=%@, msg=%@", servercmd, servercode, servermsg);
    } else {
        NSLog(@"pushMapDeviceList recervedData == nil");
    }
    
    if (![commonHttp retValueShow:[servercmd intValue] code:[servercode intValue]]) {
        return;
    }
    
}




- (void)popViewController{
    
    for (UIViewController *controller in self.navigationController.viewControllers) {
        if ([controller isKindOfClass:[DoorSystemDeviceListViewController class]]) {
            
            DoorSystemDeviceListViewController *VC =(DoorSystemDeviceListViewController *)controller;
            [self.navigationController popToViewController:VC animated:YES];
            
        }else if ([controller isKindOfClass:[BindCameraViewController class]]){
            
            BindCameraViewController *vc = (BindCameraViewController *)controller;
            [self.navigationController popToViewController:vc animated:YES];
        }
    }

    
}
#pragma mark - --------------------------UITableView dataSource--------------------------

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return self.settingPlist.count;
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return [self.settingPlist[section] count];
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    DSDeviceInfoInputTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"DSDeviceInfoInputTableViewCell"];
    NSDictionary *setting = self.settingPlist[indexPath.section][indexPath.row];
    cell.tipLabel.text = setting[@"title"];
    cell.inputTextField.placeholder = setting[@"placeholder"];
    cell.contentLabel.hidden = YES;
    cell.inputTextField.returnKeyType = UIReturnKeyDone;
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    __weak typeof(self) weakSelf = self;
    switch (indexPath.row) {
        case 0:
        {
            if (self.dsModel.uid != nil) {
                
                cell.inputTextField.text = self.dsModel.uid;
                
            }
            
            cell.textFielfEnd_block = ^(NSString *text){
                
                weakSelf.dsModel.uid = text;
                
            };
            break;
        }
        case 1:
        {
            cell.textFielfEnd_block = ^(NSString *text){
                
                weakSelf.dsModel.view_pwd = text;
                
            };
            break;
        }
        case 2:
        {
            cell.textFielfEnd_block = ^(NSString *text){
                
                weakSelf.dsModel.name = text;
                
            };
            break;
        }
        default:
            break;
    }
    
    return cell;
    
}
#pragma mark - --------------------------UITableView delegate--------------------------
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 49.f;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    
    return CGFLOAT_MIN;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    return CGFLOAT_MIN;
    
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    
}

#pragma mark - --------------------------lazy load--------------------------

- (UITableView *)tableView{
    
    if (!_tableView) {
        
        __weak UIView *superView = self.view;
        _tableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        [superView addSubview:_tableView];
        [_tableView registerNib:[UINib nibWithNibName:@"DSDeviceInfoInputTableViewCell" bundle:nil] forCellReuseIdentifier:@"DSDeviceInfoInputTableViewCell"];
        //        _tableView.separatorStyle = UITableViewCellSelectionStyleNone;//隐藏tableView的分割线
                _tableView.scrollEnabled = NO;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        
    }
    
    return _tableView;
    
}

- (NSArray *)settingPlist{
    
    if (!_settingPlist) {
        
        _settingPlist = [[NSArray alloc]initWithContentsOfFile:[[NSBundle mainBundle]pathForResource:@"AddDSInfoSetting" ofType:@"plist"]];
        
    }
    
    return _settingPlist;
    
}

- (UIButton *)nextButton{
    
    if (!_nextButton) {
        
        __weak UIView *superView = self.view;
        _nextButton = [[UIButton alloc]init];
        [superView addSubview:_nextButton];
        [_nextButton setBackgroundImage:[UIImage imageNamed:@"login_button_nor"] forState:UIControlStateNormal];
        [_nextButton setTitle:@"下一步" forState:UIControlStateNormal];
        [_nextButton addTarget:self action:@selector(addDeviceAction) forControlEvents:UIControlEventTouchDown];
        
    }
    
    return _nextButton;
    
}

- (DoorSystemModel *)dsModel{
    
    if (!_dsModel) {
        
        _dsModel = [[DoorSystemModel alloc]init];
        _dsModel.view_acc = @"admin";
        
    }
    
    return _dsModel;
    
}



- (void)setNavigationStyle{
    
    [self setLeftButtonImage:[UIImage imageNamed:@"icon_back_nor"]];
    [self setNavigationTitle:@"新增门载智能系统" titleColor:[UIColor colorWithRed:210/255.0 green:177/255.0 blue:104/255.0 alpha:1]];
    [self.tableView reloadData];
    
}

- (void)masLayoutSubview{
    
    __weak UIView *superView = self.view;
    [self.tableView mas_remakeConstraints:^(MASConstraintMaker *make) {
        
        make.edges.mas_equalTo(superView);
        
    }];
    [self.nextButton mas_remakeConstraints:^(MASConstraintMaker *make) {
       
        make.top.mas_equalTo(superView.mas_top).mas_offset(200);
        make.centerX.mas_equalTo(superView.mas_centerX);
        
    }];
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end
